package com.ellecity06.common.ktx

import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Base64
import okhttp3.internal.and
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
import java.util.Base64.getDecoder
import java.util.Base64.getEncoder
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

/**
 * @author ellecity06
 * @time 2023/4/15 17:52
 * @des
 */
fun String.md5Encrypt(upperCase: Boolean=true): String {
    if (TextUtils.isEmpty(this)) {
        return ""
    }
    var md5: MessageDigest? = null
    try {
        md5 = MessageDigest.getInstance("MD5")
        val bytes = md5.digest(toByteArray())
        var ciphertext: String? = ""
        for (b in bytes) {
            var temp = Integer.toHexString(b and 0xff)
            if (temp.length == 1) {
                temp = "0$temp"
            }
            ciphertext += temp
        }
        return if (upperCase) (ciphertext ?: "").toUpperCase(Locale.ROOT) else ciphertext ?: ""
    } catch (e: NoSuchAlgorithmException) {
        e.printStackTrace()
    }
    return ""
}

@SuppressLint("GetInstance")
fun String.aesDecode(key: String): String {
    val cipher = Cipher.getInstance("DES")
    val secretKeySpec = SecretKeySpec(key.toByteArray(), "DES")
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec)
    val decodedValue = Base64.decode(this, Base64.DEFAULT)
    val decryptedBytes = cipher.doFinal(decodedValue)
    return String(decryptedBytes)
}
